<template>
  <el-row :gutter="20" style="margin:60px 20px 20px">
    <!--仪器左侧树-->
    <el-col :span="4" :xs="24">
      <ContentWrap>
        <el-form :model="queryParams1">
          <!--左侧树上搜索框(包含模糊查询)-->
          <el-select
            v-model="queryParams1.deviceModes"
            filterable
            remote
            reserve-keyword
            :placeholder="t('searchbar.modelInfo')"
            clearable
            :remote-method="modeMethod"
            :loading="AllLoading"
            @keyup.enter="handleQuery"
            style="margin-bottom:10px"
          >
            <el-option
              v-for="item in modeList"
              :key="item.id"
              :label="item.type"
              :value="item.id"
              @click="modeHandleChange(item)"
            >
              <span style="float: left">{{ item.mode }}({{ item.deviceModeCode }})</span>
            </el-option>
          </el-select>


          <!--左侧树本体-->
          <el-tree
            :data="treeData"
            :props="defaultProps"
            :load="loadNode"
            lazy
            @node-click="handleNodeClick"
          />
        </el-form>
      </ContentWrap>
    </el-col>
      <!--协议信息-->
      <el-col :span="20">
        <ContentWrap>
          <!-- 搜索工作栏 -->
          <el-form
            class="-mb-15px"
            :model="queryParams"
            ref="queryFormRef"
            :inline="true"
            label-width="auto"
          >
<!--            <el-form-item :label="t('searchbar.type')" prop="deviceType">-->
<!--              <el-select-->
<!--                v-model="queryParams.deviceType"-->
<!--                :placeholder="t('searchbar.typeInfo')"-->
<!--                clearable-->
<!--                class="!w-240px"-->
<!--              >-->
<!--                <el-option-->
<!--                  v-for="dict in getStrDictOptions(DICT_TYPE.YQ_TYPE)"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.label"-->
<!--                  :value="dict.value"-->
<!--                />-->
<!--              </el-select>-->
<!--            </el-form-item>-->

<!--            <el-form-item :label="t('searchbar.model')" prop="deviceMode">-->
<!--              <el-input-->
<!--                v-model="queryParams.deviceMode"-->
<!--                :placeholder="t('searchbar.modelInfo')"-->
<!--                clearable-->
<!--                @keyup.enter="handleQuery"-->
<!--                class="!w-240px"-->
<!--              />-->
<!--            </el-form-item>-->



<!--            <el-form-item  :label="t('searchbar.model')" prop="deviceMode">
              <el-select
                v-model="queryParams.deviceMode"
                :placeholder="t('searchbar.modelInfo')"
                v-if="getSelectOption"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getSelectOption"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>-->


<!--            <el-form-item :label="t('searchbar.model')"  prop="deviceMode">
              <el-select
                v-model="queryParams.deviceMode"
                filterable
                remote
                reserve-keyword
                :placeholder="t('searchbar.modelInfo')"
                clearable
                class="!w-240px"
                :remote-method="modeMethod"
                :loading="AllLoading"
                @keyup.enter="handleQuery"
              >
                <el-option
                  v-for="item in modeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  @click= "modeHandleChange(item)"
                >
                  <span style="float: left">仪器型号：{{ item.label }}</span>
                </el-option>
              </el-select>
            </el-form-item>-->



            <el-form-item :label="t('formData.unitLabel')" prop="unit">
              <el-select
                v-model="queryParams.unit"
                :placeholder="t('formData.unitPlaceholder')"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.UNITS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item :label="t('formData.chMeanLabel')" prop="chMean">
              <el-input
                v-model="queryParams.chMean"
                :placeholder="t('formData.chMeanPlaceholder')"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>

            <el-form-item :label="t('formData.witsCodeLabel')" prop="witsCode">
              <el-input
                v-model="queryParams.witsCode"
                :placeholder="t('formData.witsCodePlaceholder')"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>

            <el-form-item :label="t('formData.fieldNameLabel')" prop="fieldName">
              <el-input
                v-model="queryParams.fieldName"
                :placeholder="t('formData.fieldNamePlaceholder')"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
            </el-form-item>



<!--
            <el-form-item :label="t('form.state')" prop="state">
              <el-select
                v-model="queryParams.state"
                class="!w-240px"
                clearable
                :placeholder="t('form.selectState')"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.DEVICE_STATE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>-->

<!--            <el-form-item :label="t('form.computing')" prop="calculMethod">
              <el-select
                v-model="queryParams.calculMethod"
                :placeholder="t('form.selectComput')"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.CALCUL_METHOD)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>-->

<!--            <el-form-item :label="t('form.Entertime')" prop="createTime">
              <el-date-picker
                v-model="queryParams.createTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="datetimerange"
                :start-placeholder="t('form.startDate')"
                :end-placeholder="t('form.endDate')"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-240px"
              />
            </el-form-item>-->

            <el-form-item>
              <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> {{ t('action.search') }}</el-button>
              <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> {{ t('action.reset') }}</el-button>
              <el-button
                type="primary"
                plain
                @click="openForm('create')"
                v-hasPermi="['base:standards:create']"
              >
                <Icon icon="ep:plus" class="mr-5px" /> {{ t('action.add') }}
              </el-button>

              <el-button
                type="warning"
                plain
                @click="handleImport"
              >
                <Icon icon="ep:upload" /> {{ t('action.import') }}
              </el-button>

<!--              <el-button-->
<!--                type="success"-->
<!--                plain-->
<!--                @click="handleExportStandards"-->
<!--                :loading="exportLoading"-->
<!--                v-hasPermi="['base:standards:export']"-->
<!--              >-->
<!--                <Icon icon="ep:download" class="mr-5px" /> {{ t('action.export') }}-->
<!--              </el-button>-->

            </el-form-item>
          </el-form>
        </ContentWrap>
        <ContentWrap>
          <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column :label="t('formData.serialNumberLabel')" align="center" prop="serialNumber" />
            <el-table-column :label="t('formData.fieldNameLabel')" align="center" prop="fieldName" />
            <el-table-column :label="t('formData.unitLabel')" align="center" prop="unit">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.UNITS" :value="scope.row.unit" />
              </template>
            </el-table-column>
            <el-table-column :label="t('formData.coefficientKLabel')" align="center" prop="coefficientK" />
            <el-table-column :label="t('formData.coefficientBLabel')" align="center" prop="coefficientB" />
            <el-table-column :label="t('formData.dataTypeLabel')" align="center" prop="dataType" />
            <el-table-column :label="t('formData.chMeanLabel')" align="center" prop="chMean" />
            <el-table-column :label="t('formData.calculMethodLabel')" prop="calculMethod">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.CALCUL_METHOD" :value="scope.row.calculMethod" />
              </template>
            </el-table-column>
            <el-table-column :label="t('formData.witsCodeLabel')" align="center" prop="witsCode" />
            <el-table-column :label="t('searchbar.type')" align="center" prop="deviceType">
              <template #default="scope">
                      <dict-tag :type="DICT_TYPE.YQ_TYPE" :value="scope.row.deviceType" />
              </template>
            </el-table-column>
            <el-table-column :label="t('searchbar.model')" align="center" prop="deviceMode" />


<!--            <el-table-column :label="t('searchbar.model')" align="center" prop="deviceMode">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.QY_MODEL" :value="scope.row.deviceMode" />
              </template>
            </el-table-column>-->

<!--            <el-table-column :label="t('searchbar.model')" align="center" prop="deviceMode">-->
<!--              <template #default="scope">-->
<!--                <dict-tag :type="getDictType(scope.row.deviceType)" :value="scope.row.deviceMode" />-->
<!--              </template>-->
<!--            </el-table-column>-->

            <el-table-column :label="t('formData.lengthLabel')" align="center" prop="length" />

            <el-table-column :label="t('formData.state')" align="center" prop="state">
              <template #default="scope">
                <el-tag :type="scope.row.state ? 'success' : 'danger'">
                  {{ scope.row.state ?  t('action.abled')  : t('action.disabled') }}
                </el-tag>
              </template>
            </el-table-column>


            <el-table-column :label="t('formData.remark')" align="center" prop="remark" />

            <el-table-column :label="t('formData.createTime')" align="center" prop="createTime" :formatter="dateFormatter" width="180px" />

            <el-table-column :label="t('formData.operate')" align="center"  width="100px" fixed = "right">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['base:site:update']"
                >
                  {{ t('action.edit') }}
                </el-button>
<!--                <el-button
                  link
                  type="danger"
                  @click="handleDelete(scope.row.id)"
                  v-hasPermi="['base:site:delete']"
                >
                  {{ t('action.delete') }}
                </el-button>-->
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </ContentWrap>
      </el-col>
  </el-row>

  <!-- 表单弹窗：添加/修改 -->
  <StandardsForm ref="formRef" @success="getList" />
  <!-- 对象导入模态框 -->
  <ImportForm ref="importFormRef" @success="getList" />
</template>

<script setup lang="ts">
import {getStrDictOptions, DICT_TYPE, getIntDictOptions} from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { StandardsApi, StandardsVO } from '@/api/base/standards'
import StandardsForm from './StandardsForm.vue'
import ImportForm from './ImportForm.vue'
import { ref } from 'vue';
import { ElTree, ElForm, ElFormItem } from 'element-plus';
import {da} from "element-plus/es/locale";
import { reactive, computed } from 'vue';
import type Node from "element-plus/es/components/tree/src/model/node";
import { DeviceApi, DeviceVO } from '@/api/base/device'
import DeviceBase from "@/views/base/devicebase/index.vue";

import {DeviceBaseApi, DeviceBaseVO} from "@/api/base/devicebase";


import JSZip from 'jszip';
import { saveAs } from 'file-saver';


/** 协议库 列表 */
defineOptions({ name: 'Standards' })
const message = useMessage() // 消息弹窗--------------------------
const { t } = useI18n() // 国际化----------------------


const loading = ref(true) // 列表的加载中
const list = ref<StandardsVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  fieldName: undefined,
  chMean: undefined,
  calculMethod: undefined,
  witsCode: undefined,
  unit : undefined,
  deviceType: undefined,
  deviceMode: undefined,
  state: undefined,
  createTime: [],
  input:undefined
})
const queryParams1 = reactive({
  pageNo: 1,
  pageSize: 10,
  fieldName: undefined,
  chMean: undefined,
  calculMethod: undefined,
  witsCode: undefined,
  unit: undefined,
  deviceType: undefined,
  deviceMode: undefined,
  state: undefined,
  createTime: [],
  input: undefined,
  deviceModes: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await StandardsApi.getStandardsPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()

}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.deviceType = undefined
  queryParams.deviceMode = undefined
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StandardsApi.deleteStandards(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
//
// /** 导出按钮操作 */
// const handleExportStandards = async () => {
//   try {
//     // 导出的二次确认
//     await message.exportConfirm()
//     // 发起导出
//     exportLoading.value = true
//     const data = await StandardsApi.exportStandards(queryParams)
//     download.excel(data, '协议库.xlsx')
//   } catch {
//   } finally {
//     exportLoading.value = false
//   }
// }



const handleExportStandards = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm();
    // 发起导出
    exportLoading.value = true;
    // 创建zip实例
    const zip = new JSZip();

    // 调用仪器协议导出Excel文件
    const dataStandards = await StandardsApi.exportStandards();
    // 将Excel文件内容添加到zip中
    zip.file('standards.xlsx', dataStandards, { binary: true });

    // 调用仪器型号导出Excel文件
    const dataDeviceBase = await DeviceBaseApi.exportDeviceBase();
    // 将Excel文件内容添加到zip中
    zip.file('devicebase.xlsx', dataDeviceBase, { binary: true });

    // 生成zip文件并下载
    const content = await zip.generateAsync({ type: 'blob' });
    saveAs(content, 'exportfiles.zip');
  } catch (error) {
    console.error('导出失败', error);
    message.error('导出失败，请稍后再试');
  } finally {
    exportLoading.value = false;
  }
}






/** 初始化 **/
onMounted(() => {
  getList()
})

//
// /*-------------------仪器与型号表单关联部分----------------------*/
// const getDictType = (deviceType) => {
//   const dictTypes = {
//     A: DICT_TYPE.A,
//     B: DICT_TYPE.B,
//     C: DICT_TYPE.C,
//     D: DICT_TYPE.D,
//     E: DICT_TYPE.E,
//     F: DICT_TYPE.F,
//     G: DICT_TYPE.G,
//     H: DICT_TYPE.H
//   };
//   return dictTypes[deviceType] || ''; // 返回对应的字典类型，如果不存在则返回空字符串
// };
// /*-------------------仪器与型号搜索框关联部分----------------------*/
// // 计算属性，根据 queryParams.type 返回相应的选项列表
// const getSelectOption = computed(() => {
//   const dictTypes = {
//     A: DICT_TYPE.A,
//     B: DICT_TYPE.B,
//     C: DICT_TYPE.C,
//     D: DICT_TYPE.D,
//     E: DICT_TYPE.E,
//     F: DICT_TYPE.F,
//     G: DICT_TYPE.G,
//     H: DICT_TYPE.H
//   };
//   return getStrDictOptions(dictTypes[queryParams.deviceType]);
// });





/*---------------------------获取仪器型号------------------------------*/
const AllLoading = ref(false)
const modeList = ref<DeviceBaseVO[]>([])
const queryMode = reactive({
  mode : undefined,
})
const modeMethod = async (query) => {
  AllLoading.value = true
  modeList.value = []
  AllLoading.value = false
  queryMode.mode = query
  const data =  await DeviceBaseApi.getDeviceList(queryMode)
  modeList.value = data

}
const modeHandleChange = async (item) => {
  resetQuery()
  queryParams.deviceMode = item.mode
  // 发起查询操作
  handleQuery()
}
//-----------------------------------------------------------------



/*-------------------------仪器左侧树部分----------------------------*/



const queryType = reactive({
  type : undefined,
})

// 存储树形结构的数据源
const treeData = ref([])
// 类型树形结构
const defaultProps = {
  value: 'value',
  label: 'label',
  isLeaf: 'leaf'
}

const loadNode = async (node: Node, resolve: (data: Tree[]) => void) => {
  if (node.level === 0) {
    const type = 'yq_type'
    try {
      const dataType = await StandardsApi.getDeviceType(type)
      console.log(dataType)
      return resolve(dataType)
    } catch (error) {
      console.error('Error fetching data:', error)
    }
  }
  if (node.level > 1) return resolve([])
  setTimeout(async () => {
    queryType.type = node.data.value
    try {
      const data: Tree[] = await StandardsApi.getDeviceList(queryType)
      data.forEach((i) => {
        i.leaf = true
        i.label=i.mode+"("+i.deviceModeCode+")"
      })
      resolve(data)
    } catch (error) {
      console.error('Error fetching data:', error)
    }
  }, 500)
}

const deviceModeOptions = ref([])

// 处理树节点点击事件
const handleNodeClick = async (data, node) => {
  queryParams.deviceType = undefined
  queryParams.deviceMode = undefined
  queryFormRef.value.resetFields()
  queryParams1.deviceType = undefined // 设置父节点的 value
  queryParams1.deviceMode = undefined
  queryParams1.deviceModes = undefined
  if (node.childNodes && node.childNodes.length > 0) {
    // 如果当前节点有子节点，只展开，不进行传值操作
    return
  }
  // 如果是子级节点，进行传值操作
  queryParams1.deviceType = node.parent.data.value // 设置父节点的 value
  queryParams1.deviceMode = data.mode // 设置当前节点的 value
  deviceModeOptions.value = node.parent.data.children || [] // 更新仪器型号的选项
  queryParams1.pageNo = 1
  loading.value = true
  try {
    const data = await StandardsApi.getStandardsPage(queryParams1)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
  // 发起查询操作
  // handleQuery()
}
/*---------------------------------------------------------------------------*/






/*------------------------------导入部分-----------------------------------*/
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

</script>
